﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Radiation.Common;
using System.IO;
using System.Collections;

namespace Radiation___IM.Data
{
    public class FileWorker
    {
        public FileWorker()
        {
        }

        public void processSave(File to_save)
        {
            try
            {
                StreamWriter sw = new StreamWriter(to_save.Path,false,Encoding.Unicode);

                foreach (string line in to_save.Values)
                    sw.WriteLine(line + ":" + Convert.ToBase64String(UnicodeEncoding.Unicode.GetBytes(to_save[line])));

                sw.Flush();
                sw.Close();
            }
            catch (Exception e)
            {
                Logger.Instance["error"].add("File worker - write error - " + e.ToString());
            }
        }

        public File processRead(string path)
        {
            try
            {
                StreamReader sr = new StreamReader(path);

                string temp = "-";
                int count = 0;
                Hashtable lines = new Hashtable();

                for (;;)
                {
                    temp = sr.ReadLine();
                    if (temp == null)
                        break;
                    else
                    {
                        lines.Add(count, temp);                            
                        count++;
                    }
                }

                sr.Close();

                File final = new File(path);

                for (int i = 0; i < count; i++)
                {
                    string[] splitted = ((string)lines[i]).Split(new char[] { ':' });
                    if (splitted.Length == 2)
                        final.addLine(splitted[0], UnicodeEncoding.Unicode.GetString(Convert.FromBase64String(splitted[1])));
                }

                return final;
            }
            catch (Exception e)
            {
                Logger.Instance["error"].add("File worker - read error - " + e.ToString());
            }

            return null;
        }
    }
}
